package com.example.JavaWebApi.core.aspect;

import com.alibaba.fastjson.JSON;
import com.example.JavaWebApi.core.apiinterceptors.RequestHeaderContext;
import com.example.JavaWebApi.model.entity.systemEntity.Userinfo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;

/**
 * @program: java-web-api
 * @description:
 * @author: 杨泽
 * @create: 2022-10-12 10:38
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    @Pointcut("execution(* com.example.JavaWebApi.controller..*.*(..))" +
            "&&!@annotation(com.example.JavaWebApi.core.aspect.annonation.IgnoreLog)")
    public void pointCut(){}
    @SneakyThrows
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint point){
        Userinfo userinfo=RequestHeaderContext.getUserinfo();
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        String[] strings = methodSignature.getParameterNames();
        LinkedHashMap<String,Object> linkedHashMap=new LinkedHashMap<>();
        for(int i=0;i<strings.length;i++){
            linkedHashMap.put(strings[i],point.getArgs()[i]);
        }
        log.info(methodSignature.getMethod().getName()+"执行之前用户信息:"+(userinfo==null?"":JSON.toJSONString(userinfo)));
        log.info(methodSignature.getMethod().getName()+"实参:"+JSON.toJSONString(linkedHashMap));
        Object result= point.proceed();
        log.info(methodSignature.getMethod().getName()+"执行之后:"+ JSON.toJSONString(result));
        return result;

    }
}